package org.kleathome.dcpu16.asm;

import org.kleathome.dcpu16.DCPU16Value;

public class ASMLabel extends DCPU16Value
{
	public String jumpWhere;
	public char jumpAddress;
	public boolean jumpFar = true; 

	public ASMLabel(String label)
	{
		jumpWhere = label;
		jumpAddress = 0xFFFF;
	}
	
	@Override
	public char getValue()
	{
		return 0;
	}
	@Override
	public void setValue(char in)
	{
	}
	@Override
	public int getCycleCost()
	{
		return 0;
	}
	
	public String toString()
	{
		return "Label " + jumpWhere + " [0x" + Integer.toHexString(jumpAddress) + "]";
	}

	@Override
	public int getInstructionWords()
	{
		return jumpFar?1:0;
	}

	public void updateJumpAddresses()
	{
		char thisAddress = ASMParser.getInstructionPointer(this);
		jumpAddress = ASMParser.getLabelAddress(jumpWhere);
		if (!ASMParser.optimizedFlag)
			return;
		int distance = Math.abs(thisAddress - jumpAddress);
		if (distance < 0x1F && jumpFar == true)
		{
			jumpFar = false;
			ASMParser.decreaseInstructionPointer();
			//System.out.println("optimize here --> " + distance);
			ASMParser.moveJumpAddress(thisAddress);
		}
		//System.out.println("ASMLabel: " + jumpWhere + " --> 0x" + Integer.toHexString(jumpAddress));
	}

	@Override
	public int getOpCode()
	{
		if (jumpFar)
			return 0x1f;
		else
			return 0x20 + jumpAddress;
	}

	@Override
	public char getDataCode()
	{
		return jumpAddress;
	}
}
